package com.example.bookdemo.config;

import com.example.bookdemo.model.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    //advice表示执行

    //默认有一个对象,方法直接提供了
    @Autowired
    private ObjectMapper objectMapper;//json转换工具,对象转json

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        log.info("用来判断要不要对接口进行封装");
        return true;//要对所有的接口都封装        false 不是
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        log.info("在正文之前要做什么");
        if(body instanceof String ){
            try {
                return objectMapper.writeValueAsString(body);//转换成json
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        if(body instanceof Result<?>){
            return body;
        }
        return Result.success(body);//这个对于body是String类型的要特殊处理
    }
}
